// pages/singlelamp_asset/singlelamp_asset.js
var app=getApp()

//日历用到的变量
const date = new Date()
const years = []
const months = []
const days = []

// for (let i = 1990; i <= date.getFullYear(); i++) {
//   years.push(i)
// }
for (let i = date.getFullYear(); i >= 2010; i--) {
  years.push(i)
}

for (let i = 1; i <= 12; i++) {
  var k = i;
  if (0 <= i && i <= 9) {
    k = "0" + (i);
  } else {
    k = (i);
  }
  months.push(k)
}

for (let i = 1; i <= 31; i++) {
  var k = i;
  if (0 <= i && i <= 9) {
    k = "0" + (i);
  } else {
    k = (i);
  }
  days.push(k)
}
//日历变量

var page = 0;
var page_size = 10
let header = {
  'content-type': 'application/x-www-form-urlencoded',
  'cookie': "openid=" + app.globalData.openid
}
var GetList = function (that, type) {
  that.setData({
    hidden: false
  });

  let url_str = ''
  if(that.data.currentIndex == 1){
    url_str = 'https://119.3.46.145/server/GetDeviceStatusHistory'
  }

  if (that.data.currentIndex == 2) {
    url_str = 'https://119.3.46.145/server/GetAlarmHistory'
  }
  wx.request({   
    //参数devNo: 868221043220329 start: 0 num: 20 startTime:2020-01-08 00:00:00 endTime:2020-01-08 23:59:59
    url: url_str,
    method: 'post',
    data:{
      userid:app.globalData.userid,
      devNo: parseInt(that.data.devNo),
      start:page_size * page,
      num:page_size,
      startTime:that.data.startTime,
      endTime:that.data.endTime,
    },
    header: header,
    success: function (res) {
      let data = JSON.parse(res.data.data);    
      if (data.length == 0) {
        that.setData({
          hidden: true,
          // list:[]
        });
        return;
      }

      //tmp_list 再正常状态是需要push下一页，所以需要赋值是 that.data.list,
      var tmp_list = [];

      if(type!='filter'){
        tmp_list = that.data.list;
      }

      for (var i = 0; i < data.length; i++) {
        tmp_list.push(data[i]);
      }
      that.setData({
        list: tmp_list,
        hidden: true
      });
      // console.log(that.data.list, 'that.data.list');
      page++;
      
    }
  });
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    devNo:'',
    current_info:{},
    currentIndex: 0,
    // "firstList": ["LXT", "LXT", "LXT", "LXT", "LXT", "LXT"],
    // "secondList": ["GFF", "GFF", "GFF", "GFF", "GFF", "GFF", "GFF", "GFF"],
    hidden: true,
    list: [],
    scrollTop: 0,
    scrollHeight: 0,

    //日历变量
    DialogTitle: "日期",
    years: years,
    year: date.getFullYear(),
    months: months,
    month: 2,
    days: days,
    day: 2,
    value: [9999, 1, 1],
    // startTime: date.getFullYear()+'-01-01 00:00:00',
    // endTime: date.getFullYear()+'-01-01 23:59:59'
    startTime: '',
    endTime: '',
    date_array:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let lampmid = options.mid;

    //let tmp_lamp_list = that.data.lamp_list;
    // let cur_devNo = -1;

    //第一步获取改设备的devNo
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    }

    wx.request({
      url: 'https://119.3.46.145/server/FindSingleLight?id=' + lampmid,
      method: 'POST',
      header: header,
      success: res => {
        //console.log(res, "res");
        //{"data":"[{\"LightType\":\"2\",\"MaxCurrent\":\"100.0\",\"turnOfftime\":\"05:00:00\",\"devNo\":\"868221043829715\",\"groupID\":\"1\",\"MinCurrent\":\"50.0\",\"Latitude\":\"32.3763\",\"Longitude\":\"119.387566\",\"Name\":\"无锡测试\",\"RatedPower\":\"0.0\",\"LightNo\":\"\",\"UserId\":\"922aeb81-29c8-41ba-9f82-36d9abb33265\",\"LightBrand\":\"\",\"id\":\"32\",\"turnOntime\":\"01:00:00\"}]"}   
        let result = JSON.parse(res.data.data)[0];        

        that.setData({
          devNo: result.devNo
        });

        wx.request({
          url: 'https://119.3.46.145/server/GetLastInfo',
          method:'post',
          header:header,
          data:{
            devNo:that.data.devNo
          },
          success:res=>{
            let data = JSON.parse(res.data.data);
            let current_info = {}
            if(data.length != 0){
              that.setData({
                current_info:data[0]
              });
            }
          }
        })
      }
    }); 
  },

  //swiper切换时会调用
  pagechange: function (e) {
    //console.log(e, "e");
    if ("touch" === e.detail.source) {
      let currentPageIndex = this.data.currentIndex
      currentPageIndex = (currentPageIndex + 1) % 2
      //console.log(currentPageIndex, "currentPageIndex");
      this.setData({
        currentIndex: currentPageIndex
      });
    }
  },

  //用户点击tab时调用
  titleClick: function (e) {
    let that = this;
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    }

      //页面变量全部重置
      this.setData({
        //拿到当前索引并动态改变
        currentIndex: e.currentTarget.dataset.idx,
        startTime:'',
        endTime:'',
        list:[]
      })

      if(e.currentTarget.dataset.idx == 1){
        //充值起始页
        page = 0;
        that.setData({
          list:[]
        });

        
        //请求状态与变更日志
        wx.getSystemInfo({
          success: function (res) {           
            that.setData({
              scrollHeight: res.windowHeight
            });
          }
        });

        GetList(that);
      }

      if (e.currentTarget.dataset.idx == 2) {
        //重置起始页
        page = 0;
        that.setData({
          list: []
        });
        
        //请求告警日志
        wx.getSystemInfo({
          success: function (res) {
            that.setData({
              scrollHeight: res.windowHeight
            });
          }
        });

        GetList(that);
      }   
  },

  OPEN: function () {
    let that = this;
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    }
    wx.request({
      url: "https://119.3.46.145/server/addMission",
      method: "post",
      header: header,
      data: {
        userid: app.globalData.userid,
        devNo: that.data.devNo,
        type: 0
      },
      success: function (response) {
        let obj = response.data.error;
        if (obj == 0) {
          // alert("已加入任务队列，等待执行");
          // refreshTask();
          wx.showModal({
            title: '提示',
            content: '已加入任务队列，等待执行',
            showCancel: false
          });
        }
      }
    })
  },

  CLOSE: function () {
    let that = this;
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    }
    wx.request({
      url: "https://119.3.46.145/server/addMission",
      method: "post",
      header: header,
      data: {
        userid: app.globalData.userid,
        devNo: that.data.devNo,
        type: 1
      },
      success: function (response) {
        let obj = response.data.error;
        if (obj == 0) {
          // alert("已加入任务队列，等待执行");
          // refreshTask();
          wx.showModal({
            title: '提示',
            content: '已加入任务队列，等待执行',
            showCancel: false
          });
        }
      }
    })
  },

  AUTO: function () {
    let that = this;
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    }
    wx.request({
      url: "https://119.3.46.145/server/addMission",
      method: "post",
      header: header,
      data: {
        userid: app.globalData.userid,
        devNo: that.data.devNo,
        type: 2
      },
      success: function (response) {
        let obj = response.data.error;
        if (obj == 0) {
          // alert("已加入任务队列，等待执行");
          // refreshTask();
          wx.showModal({
            title: '提示',
            content: '已加入任务队列，等待执行',
            showCancel: false
          });
        }
      }
    })
  },

  MANUAL: function () {
    let that = this;
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    }
    wx.request({
      url: "https://119.3.46.145/server/addMission",
      method: "post",
      header: header,
      data: {
        userid: app.globalData.userid,
        devNo: that.data.devNo,
        type: 3
      },
      success: function (response) {
        let obj = response.data.error;
        if (obj == 0) {
          wx.showModal({
            title: '提示',
            content: '已加入任务队列，等待执行',
            showCancel: false
          });
        }
      }
    })
  },

  bindDownLoad: function () {
    var that = this;
    //console.log(page, "page");
    GetList(that);
  },

  scroll: function (event) {
    this.setData({
      scrollTop: event.detail.scrollTop
    });
  },

  refresh: function (event) {
    page = 0;
    this.setData({
      list: [],
      scrollTop: 0
    });
    GetList(this)
  },

  _text: function () {    
    var that = this;
    that.calendar.showDialog();
  },

  //确定按钮的返回值
  _cancelEvent(e) {
    let that = this;   
    this.calendar.hideDialog();
    if (that.data.currentIndex == 0) {
      return;
    }

    let array = that.data.date_array;   
   
    let date_time = '';
    let year = '';
    let month = '';
    let day = '';
    year = years[array[0]];
    month = months[array[1]];
    day = days[array[2]];

    that.setData({
      startTime: year + '-' + month + '-' + day + " 00:00:00",
      endTime: year + '-' + month + '-' + day + " 23:59:59"
    });
  
    page = 0;//重置页面 page从0开始
    GetList(that, 'filter');
  },

  _cancelEvents(e) {    
    let that = this;
    that.setData({
      date_array:e.detail
    });

    console.log(e.detail, "e.detail");
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.calendar = this.selectComponent("#calendar");
  },

  goto_task_queue:function(){
    wx.switchTab({
      url: '../task_queue/task_queue',
    })
  },

  goto_index: function () {
    wx.switchTab({
      url: '../index/index',
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})